package com.mcp.converter.domain.rule.compatibility.function;

import com.mcp.converter.domain.checker.IncompatibilityDetail;
import com.mcp.converter.shared.response.sql.SQLElement;
import com.mcp.converter.domain.rule.compatibility.AbstractFunctionRule;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * XMLAGG, XMLELEMENT等XML函数兼容性规则
 * OceanBase对XML函数的支持有限
 * @author zengxiong
 */
public class XmlFunctionsRule extends AbstractFunctionRule {

    private static final String RULE_ID = "FN014";
    private static final String RULE_NAME = "XML函数兼容性";
    private static final String RULE_DESCRIPTION = "OceanBase对XML相关函数的支持有限或存在差异。";

    private static final Set<String> INCOMPATIBLE_XML_FUNCTIONS = new HashSet<>(Arrays.asList(
        "XMLCDATA", "XMLCOMMENT", "XMLCONCAT", "XMLDOCUMENT",
        "XMLFOREST", "XMLITERATE", "XMLNAMESPACES",
        "XMLPI", "XMLQUERY", "XMLROOT", "XMLSCHEMA_VALID",
        "XMLTRANSFORM", "XMLTYPE", "XMLVALIDATE"
    ));

    public XmlFunctionsRule() {
        super(RULE_ID, RULE_NAME, RULE_DESCRIPTION);
        setIncompatibilityDetail(
                "OceanBase对XML相关函数（如 XMLAGG, XMLELEMENT, XMLFOREST, XMLCONCAT, XMLPARSE, XMLSERIALIZE等）的支持可能不完整，或者其行为、可用选项与Oracle存在显著差异。",
                "使用这些XML函数的查询可能在OceanBase中无法执行、返回错误、或产生与Oracle不同的XML结构或内容。某些XML特性、命名空间处理或序列化选项可能不受支持。",
                "仔细评估在OceanBase中使用XML函数的必要性。验证目标OceanBase版本对所需XML函数的支持程度和具体行为。如果支持有限或不兼容，考虑在应用层面处理XML生成/聚合，寻找替代的数据表示方法，或简化XML操作。",
                IncompatibilityDetail.Severity.HIGH
        );
    }

    @Override
    public boolean matches(Object target) {
        if (target instanceof SQLElement) {
            SQLElement element = (SQLElement) target;
            if (isFunctionElement(element)) {
                String functionName = element.getName().toUpperCase();
                return INCOMPATIBLE_XML_FUNCTIONS.contains(functionName);
            }
        }
        return false;
    }
    
    @Override
    public Set<String> getIncompatibleFunctions() {
        return new HashSet<>(INCOMPATIBLE_XML_FUNCTIONS);
    }
}
